<template>
  <a-modal :visible="visible" title="话题导入" @cancel="cancelChange">
    <a-form>

      <template v-if="PlatFormValue != 'xiaohongshu'">
        <a-form-item label="关键词组" v-bind="validateInfos.ai_keyword_group_id">
          <a-select style="width: 150px" allowClear v-model:value="modelRef.ai_keyword_group_id" placeholder="选择关键词组"
            :options="options" @change="groupSelChange"></a-select>
        </a-form-item>
        <div style="display: flex">
          <a-form-item style="margin-bottom: 0 !important">
            <span style="margin-right: 3px; color: var(--ss-primary-color)">#添加话题</span>
          </a-form-item>
          <a-form-item style="margin-bottom: 0 !important; flex: 1">
            <a-select v-model:value="modelRef.hashtag_name" mode="tags" :maxTagTextLength="10" :maxTagCount="5"
              :token-separators="[',']" @change="tagChange($event)" :bordered="false" placeholder="输入话题按回车键选中"
              style="width: 100%" :options="keyWordsList" optionLabelProp="label"></a-select>
          </a-form-item>
        </div>
      </template>

      <template v-else>
        <a-form-item>
          <template #label>
            <span class="mr-5">话题</span>
            <a-tooltip>
              <template #title>
                <span>需要先选择账号</span>
              </template>
              <QuestionCircleOutlined />
            </a-tooltip>
          </template>
          <a-select v-model:value="selectTopicList" :disabled="!accountId" show-search @search="handleSearch"
            :filter-option="false" @change="handleChange" mode="multiple" :maxTagCount="20" placeholder="请选择话题">
            <a-select-option :disabled="selectTopicList.length > 19 &&
              !selectTopicList.includes(item.key)
              " :value="item.key" v-for="(item, index) in topicList" :key="item.key">{{ item.name
              }}</a-select-option>
          </a-select>
          <div class="mt-5 text-gray-6">您可以添加20个话题</div>
        </a-form-item>
      </template>
    </a-form>
    <template #footer>
      <a-button type="primary" @click="confirmImport">确定导入</a-button>
    </template>
  </a-modal>
</template>

<script>
import {
  defineComponent,
  ref,
  reactive,
  toRefs,
  createVNode,
  computed,
  onMounted,
  watch,
} from "vue";
import request from "@/common/utils/request";
import { Form, message } from "ant-design-vue";
import { uniqBy } from "lodash-es";
import {
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { useDebounceFn } from "@vueuse/core";
const useForm = Form.useForm;

export default defineComponent({
  name: "TopicImportModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 发布类型
    PlatFormValue: {
      type: String,
      default: "",
    },
    // 用户列表
    accountList: {
      type: [],
      default: () => {
        return [];
      },
    },
  },
  components: {
    QuestionCircleOutlined
  },
  setup(props, { emit }) {
    const state = reactive({
      count: 0,
      options: [],
      keyWordsList: [],

      // 全部的话题数组(包括历史和最新的话题数组)
      totalTopicList: [],

      // 话题 v-model 绑定的数组
      selectTopicList: [],

      // select, 展示的每一个话题
      topicList:[]
    });

    const modelRef = reactive({
      ai_keyword_group_id: undefined,
      hashtag_name: undefined,
    });
    const rulesRef = reactive({
      ai_keyword_group_id: [
        {
          required: false,
          message: "请选择关键词组",
        },
      ],
    });

    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    // 获取关键词组下拉列表
    const getOptionList = () => {
      request
        .get("/work_ai", "/user/filmrelease/ai/keyword", { pagesize: 0 })
        .then((res) => {
          state.options = res.result.data.map((item) => {
            return {
              label: item.extraction_word,
              value: item.id,
            };
          });
        });
    };

    const groupSelChange =()=>{
      if (modelRef.ai_keyword_group_id) {
        modelRef.hashtag_name = undefined
        let params = {
          page: 0,
          ai_keyword_id: modelRef.ai_keyword_group_id,
          word: "",
        };
        request
          .get("/work_ai", "/user/filmrelease/ai/keywordMerge/list", params)
          .then((successRes) => {
            state.keyWordsList = successRes?.result?.map(
              (ele) => {
                return {
                  value: ele.id,
                  label: ele.merge_keyword,
                };
              }
            );
          })
          .catch((errorRes) => {
            state.titleList[index].isSpining = false;
          });
      }
    }

    const tagChange = (event) => {
      if (event.length && event[event.length - 1].length > 10) {
        message.warning("单个话题长度不能超过10个字符");
        modelRef.hashtag_name[modelRef.hashtag_name.length - 1] =
          modelRef.hashtag_name[modelRef.hashtag_name.length - 1].substring(
            0,
            10
          );
        modelRef.hashtag_name = modelRef.hashtag_name.map((tag) => {
          const option = state.keyWordsList?.find((ele) => ele.value == tag);
          return option ? option.label : tag;
        });
      }
      if (event.length > 5) {
        message.warning("最多添加5个标签");
        modelRef.hashtag_name = modelRef.hashtag_name.filter(
          (tag, index) => index < 5
        );
      }
    };

    const cancelChange = () => {
      emit("closeChange");
    };

    const confirmImport = () => {
      if (props.PlatFormValue == 'xiaohongshu') {
        console.log(state.totalTopicList, 'totalTopicList');
        console.log(state.selectTopicList, 'selectTopicList');
        console.log(state.topicList, 'topicList');
        const items = state.totalTopicList.filter(item => state.selectTopicList.includes(item.key))
        console.log('筛选出的items', items);
        emit('XHS_importChange', items )
      } else {
        validate().then(() => {
            emit("importChange", {
              changeData: {
                ai_keyword_group_id: modelRef.ai_keyword_group_id,
                hashtag_name: modelRef.hashtag_name,
              },
            });
        });
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          if (props.PlatFormValue == 'xiaohongshu') {
            accountId.value && debouncedFn()
          } else {
            getOptionList();
          }
        } else {
          modelRef.hashtag_name = undefined;
          modelRef.ai_keyword_group_id = undefined;
        }
      }
    );


    // 用户id
    const accountId = computed(() => {
      if (!props.accountList.length) {
        return ''
      }
      return props.accountList[0].id
    })
    // 小红书获取话题
    const getTopicList = async (keyword = "") => {
      const { result } = await request.post(
        "/work_ai",
        "/org/platform/account/topic",
        { id: accountId.value, keyword }
      );
      console.log(result, '话题123123');
      
      state.topicList = result;
      state.totalTopicList.push(...state.topicList);
      state.totalTopicList = uniqBy(state.totalTopicList, "key");
    };

    const handleChange = (e) => {
      console.log(e,'选择的话题');
      
      if (e && e.length > 19) {
        message.warning("最多选择20个话题");
      }
    };
    const debouncedFn = useDebounceFn((e) => {
      getTopicList(e);
    }, 500);

    const handleSearch = (keyword) => {
      debouncedFn(keyword);
    };

    return {
      ...toRefs(state),
      handleChange,
      accountId,
      handleSearch,
      confirmImport,
      validateInfos,
      resetFields,
      modelRef,
      cancelChange,
      tagChange,
      groupSelChange
    };
  },
});
</script>

<style lang="less" scoped></style>
